<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use app\common\library\Wechat;
use app\common\model\User as ModelUser;
use app\common\model\user\Address;
use fast\Http;
use fast\Random;
use think\Cache;
use think\Config;
use think\Validate;

/**
 * 会员接口
 */
class User extends Api
{
    protected $noNeedLogin = ['login', 'wxLogin', 'mobilelogin', 'register', 'resetpwd', 'changeemail', 'changemobile', 'third', 'qiqiaoToken'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();

        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }
    }
    /**
     * 微信小程序登录
     *
     * @param string $code 微信授权code
     * @param string $phoneCode 电话授权code
     * @param string $nickname 昵称
     * @param string $avatar 头像
     * @param string $qr_code 邀请码
     * @return array
     */
    public function wxLogin()
    {
        $params = $this->request->param();
        extract($params);
        // 入参
        if (empty($code) ||  empty($phoneCode)) {
            $this->error('缺少必要参数!');
        }
        $result = [];
        try {
            $wechat = new Wechat('wxMiniProgram');
            $decryptSession = $wechat->code($code);
            if (!isset($decryptSession['session_key'])) {
                exception($decryptSession['errmsg']);
            }
            if (!$decryptSession || !isset($decryptSession['openid'])) {
                exception('未获取到登录状态,请重试!');
            }
            if (empty($decryptSession['openid'])) {
                exception('code错误,请重试!');
            }
            // 分参
            $decrypt = $wechat->getAccessToken();
            $token = $decrypt['access_token'];
            $url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=$token";
            $client = new \GuzzleHttp\Client();
            $response = $client->post($url, [
                'json' => [        //参数组
                    'code' => $phoneCode
                ]
            ]);
            $res = $response->getBody();
            $res = json_decode($res, 1);
            if ($res['errcode'] == 0) {
                $phone = $res['phone_info'];
            } else {
                exception('失败:' . $res['errmsg']);
            }
            $user = \app\common\model\User::get([
                'openid'   => $decryptSession['openid']
            ]);
            if (!empty($user)) {
                if ($user->status != 'normal') {
                    exception(__('Account is locked'));
                }
                $user->save();
                // 直接登陆
                $result = $this->auth->direct($user->id, $token);
            } else {
                if (isset($qr_code) && !empty($qr_code)) {
                    $decryptSession['qr_code'] = $qr_code;
                }
                $decryptSession['phoneNumber'] = $phone['phoneNumber'] ?? '';
                $decryptSession['nickname'] = $nickname ?? '';
                // 写入个人数据
                $result = $this->auth->oauthRegister($decryptSession);
            }
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        if ($result) {
            $this->success('授权登录成功', $this->auth->getUserInfo());
        } else {
            $this->error('授权登录失败了!' . $this->auth->getError());
        }
    }
    /**
     * 会员中心
     */
    public function index()
    {
        $userInfo = ModelUser::get($this->auth->id);
        $this->success('', $userInfo);
    }
    /**
     * 会员登录
     *
     * @ApiMethod (POST)
     * @param string $account  账号
     * @param string $password 密码
     */
    public function login()
    {
        $account = $this->request->post('account');
        $password = $this->request->post('password');
        if (!$account || !$password) {
            $this->error(__('Invalid parameters'));
        }
        $ret = $this->auth->login($account, $password);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }
    /**
     * 手机验证码登录
     *
     * @ApiMethod (POST)
     * @param string $mobile  手机号
     * @param string $captcha 验证码
     */
    public function mobilelogin()
    {
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (!Sms::check($mobile, $captcha, 'mobilelogin')) {
            $this->error(__('Captcha is incorrect'));
        }
        $user = \app\common\model\User::getByMobile($mobile);
        if ($user) {
            if ($user->status != 'normal') {
                $this->error(__('Account is locked'));
            }
            //如果已经有账号则直接登录
            $ret = $this->auth->direct($user->id);
        } else {
            $ret = $this->auth->register($mobile, Random::alnum(), '', $mobile, []);
        }
        if ($ret) {
            Sms::flush($mobile, 'mobilelogin');
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 注册会员
     *
     * @ApiMethod (POST)
     * @param string $username 用户名
     * @param string $password 密码
     * @param string $email    邮箱
     * @param string $mobile   手机号
     * @param string $code     验证码
     */
    public function register()
    {
        $username = $this->request->post('username');
        $password = $this->request->post('password');
        $email = $this->request->post('email');
        $mobile = $this->request->post('mobile');
        $code = $this->request->post('code');
        if (!$username || !$password) {
            $this->error(__('Invalid parameters'));
        }
        if ($email && !Validate::is($email, "email")) {
            $this->error(__('Email is incorrect'));
        }
        if ($mobile && !Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        $ret = Sms::check($mobile, $code, 'register');
        if (!$ret) {
            $this->error(__('Captcha is incorrect'));
        }
        $ret = $this->auth->register($username, $password, $email, $mobile, []);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Sign up successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 退出登录
     * @ApiMethod (POST)
     */
    public function logout()
    {
        if (!$this->request->isPost()) {
            $this->error(__('Invalid parameters'));
        }
        $this->auth->logout();
        $this->success(__('Logout successful'));
    }

    /**
     * 修改会员个人信息
     *
     * @ApiMethod (POST)
     * @param string $avatar   头像地址
     * @param string $username 用户名
     * @param string $nickname 昵称
     * @param string $bio      个人简介
     */
    public function profile()
    {
        $user = $this->auth->getUser();
        $username = $this->request->post('username');
        $nickname = $this->request->post('nickname');
        $bio = $this->request->post('bio');
        $avatar = $this->request->post('avatar', '', 'trim,strip_tags,htmlspecialchars');
        if ($username) {
            $exists = \app\common\model\User::where('username', $username)->where('id', '<>', $this->auth->id)->find();
            if ($exists) {
                $this->error(__('Username already exists'));
            }
            $user->username = $username;
        }
        if ($nickname) {
            $exists = \app\common\model\User::where('nickname', $nickname)->where('id', '<>', $this->auth->id)->find();
            if ($exists) {
                $this->error(__('Nickname already exists'));
            }
            $user->nickname = $nickname;
        }
        $user->bio = $bio;
        $user->avatar = $avatar;
        $user->save();
        $this->success();
    }

    /**
     * 修改邮箱
     *
     * @ApiMethod (POST)
     * @param string $email   邮箱
     * @param string $captcha 验证码
     */
    public function changeemail()
    {
        $user = $this->auth->getUser();
        $email = $this->request->post('email');
        $captcha = $this->request->post('captcha');
        if (!$email || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::is($email, "email")) {
            $this->error(__('Email is incorrect'));
        }
        if (\app\common\model\User::where('email', $email)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Email already exists'));
        }
        $result = Ems::check($email, $captcha, 'changeemail');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->email = 1;
        $user->verification = $verification;
        $user->email = $email;
        $user->save();

        Ems::flush($email, 'changeemail');
        $this->success();
    }

    /**
     * 修改手机号
     *
     * @ApiMethod (POST)
     * @param string $mobile  手机号
     * @param string $captcha 验证码
     */
    public function changemobile()
    {
        $user = $this->auth->getUser();
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (\app\common\model\User::where('mobile', $mobile)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Mobile already exists'));
        }
        $result = Sms::check($mobile, $captcha, 'changemobile');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->mobile = 1;
        $user->verification = $verification;
        $user->mobile = $mobile;
        $user->save();

        Sms::flush($mobile, 'changemobile');
        $this->success();
    }


    /**
     * 重置密码
     *
     * @ApiMethod (POST)
     * @param string $mobile      手机号
     * @param string $newpassword 新密码
     * @param string $captcha     验证码
     */
    public function resetpwd()
    {
        $type = $this->request->post("type");
        $mobile = $this->request->post("mobile");
        $email = $this->request->post("email");
        $newpassword = $this->request->post("newpassword");
        $captcha = $this->request->post("captcha");
        if (!$newpassword || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        //验证Token
        if (!Validate::make()->check(['newpassword' => $newpassword], ['newpassword' => 'require|regex:\S{6,30}'])) {
            $this->error(__('Password must be 6 to 30 characters'));
        }
        if ($type == 'mobile') {
            if (!Validate::regex($mobile, "^1\d{10}$")) {
                $this->error(__('Mobile is incorrect'));
            }
            $user = \app\common\model\User::getByMobile($mobile);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Sms::check($mobile, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Sms::flush($mobile, 'resetpwd');
        } else {
            if (!Validate::is($email, "email")) {
                $this->error(__('Email is incorrect'));
            }
            $user = \app\common\model\User::getByEmail($email);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Ems::check($email, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Ems::flush($email, 'resetpwd');
        }
        //模拟一次登录
        $this->auth->direct($user->id);
        $ret = $this->auth->changepwd($newpassword, '', true);
        if ($ret) {
            $this->success(__('Reset password successful'));
        } else {
            $this->error($this->auth->getError());
        }
    }



    /**
     * 获取用户收货地址
     *
     * @ApiMethod (GET)
     */
    public function getUserAddress()
    {
        $uid = $this->auth->id;

        $data = Address::getUserAddress($uid);
        $this->success('获取成功', $data);
    }
    /**
     * 获取用户默认地址
     *
     * @ApiMethod (GET)
     */
    public function getDefaultAddress()
    {
        $uid = $this->auth->id;
        $list = Address::getDefaultAddress($uid);
        $this->success('获取成功', $list);
    }
    /**
     * 设置用户默认地址
     *
     * @ApiMethod (POST)
     * @param string $id  地址id
     * 
     */
    public function setDefaultAddress()
    {
        $post = $this->request->post();
        extract($post);
        if (!isset($id) || empty($id)) {
            $this->error('参数错误');
        }
        $uid = $this->auth->id;
        Address::setDefaultAddress($id, $uid);
        $this->success('设置成功');
    }
    /**
     * 添加收货地址
     *
     * @ApiMethod (POST)
     * @param string $contact  收货人
     * @param string $telephone  手机号
     * @param string $province  省
     * @param string $city  市
     * @param string $area  区
     * @param string $address  地址
     * @param string $longitude  经度
     * @param string $latitude  纬度
     * @param string $is_default  纬度
     * 
     */
    public function addAddress()
    {
        $post = $this->request->post();
        $validate = validate('user.Address'); //使用助手函数
        $result = $validate->check($post);
        if (!$result) {
            $this->error($validate->getError());
        }
        $post['user_id'] = $this->auth->id;
        $res = Address::AddAddress($post);
        if ($res !== false) {
            $this->success('提交成功', $res);
        }
        $this->error('提交失败');
    }
    /**
     * 删除用户收货地址
     *
     * @ApiMethod (POST)
     * @param string $id  地址id
     * 
     */
    public function delAddress()
    {
        $post = $this->request->post();
        extract($post);
        if (!isset($id) || empty($id)) {
            $this->error('参数错误');
        }
        $data = Address::get($id);
        $data->delete();
        $this->success('删除成功', $data);
    }
}
